package travianBot.botScripts;

import java.util.HashMap;

import org.apache.log4j.Logger;

import travianBot.TravianBot;
import travianBot.TravianBotException;

public class ResourceScript extends TravianScript {

	String[] 	resourceArray;
	int[]		levelArray;
	static Logger log=Logger.getLogger(BuildingScript.class);
	
	public ResourceScript(String csvLine){
		init(csvLine);
	}
	
	public void init(String csvLine){
		String[] tokens = csvLine.split(",");
		
		int cursorToken 		= Integer.parseInt(tokens[0]);
		String villageNameToken = tokens[1];
		String typeToken 		= tokens[2];
		
		this.cursorPosition = cursorToken;
		this.villageName = villageNameToken;
		this.type = typeToken;
		
		// collect the remaining entries
		int tailLength = tokens.length - 3;
		
		String[] localResourceArray 		= new String[tailLength];
		int[] 	localResourceLevelArray 	= new int[tailLength];
		
		// collect the tail which is variable length
		String[] resourcePieces;
		String   resource;
		int      level;
		for (int i = 3; i < tokens.length; i++) {
			resourcePieces = tokens[i].split(":");
			localResourceArray[i-3]=resourcePieces[0];
			
			if(resourcePieces.length > 1){
				level = Integer.parseInt(resourcePieces[1]);
			}else{
				level = -1;
			}
			localResourceLevelArray[i-3] = level;
		}
		log.debug("creating resource script from: "+csvLine);
		log.debug("creating resource using tokens: "+cursorToken+","+villageNameToken+","+typeToken+","+localResourceArray+","+localResourceLevelArray);
		
		this.resourceArray = localResourceArray;
		this.levelArray = localResourceLevelArray;
	}
	
	public void runScript(TravianBot travianBot, HashMap<String,String> sessionInfoMap) throws TravianBotException{
		boolean passed = travianBot.upgradeResource(this.villageName, getCurrentResourceUpgrade()); 		
		// update script
		if(passed){
			incrementResourceUpgradecounter();
		}	
	}
	
	public String getCurrentResourceUpgrade(){
		return resourceArray[cursorPosition];
	}
	
	public int getCurrentResourceLevel(){
		return levelArray[cursorPosition];
	}
	
	public void incrementResourceUpgradecounter(){
		cursorPosition = (cursorPosition + 1)% resourceArray.length;
	}
	
	public String[] getResourceArray() {
		return resourceArray;
	}
	public void setResourceArray(String[] resourceArray) {
		this.resourceArray = resourceArray;
	}
	public int[] getLevelArray() {
		return levelArray;
	}
	public void setLevelArray(int[] levelArray) {
		this.levelArray = levelArray;
	}		

}

